import {
  Checkbox,
  CheckboxGroup,
  Label,
  Picker,
  Textarea,
  View,
} from "@tarojs/components";
import {
  AbstractImage,
  C13BottomDock,
  Icon,
  Paragraph,
  PriceView,
  UserSubPageBase,
} from "@/components";
import { CartItemShape } from "@/data/user/userTypes";
import { colors } from "@/data/shared/colors";
import { navigateTo } from "@/utils/navigation";
import { useEffect, useState } from "react";
import style from "./index.module.scss";
import { useUserInfo } from "@/store/userDataContext";

type RefundListProps = {
  items: CartItemShape[];
  refundReasons: string[];
  handleSubmit: Function;
};

const C41RefundList = ({
  items,
  refundReasons,
  handleSubmit,
}: RefundListProps) => {
  const { dispatchUserDataAction } = useUserInfo();
  const [checkedItems, setCheckedItems] = useState<number[]>([]);
  const [reason, setReason] = useState("");
  const [additional, setAdditional] = useState("");

  const checkAll = () => {
    setCheckedItems(items.map((item) => item.productId));
  };

  // Initialize state once data comes in
  useEffect(() => {
    checkAll();
  }, [items.length]);

  useEffect(() => {
    dispatchUserDataAction({
      type: "REFUND_SELECT",
      data: checkedItems,
    });
  }, [checkedItems.length]);

  const handleCheckbox = (checked, item) => {
    const newCheckItems = checked
      ? [...checkedItems, item.productId]
      : checkedItems.filter((val) => {
          return val !== item.productId;
        });
    setCheckedItems(newCheckItems);
  };

  const hasReason = !!reason;
  const isAllChecked = items.length === checkedItems.length;

  return (
    <UserSubPageBase title="申请退款" scrollable>
      <View className={style["refund-list-wrapper"]}>
        {/* Cart item listing */}
        <View className={`${style["section"]} ${style["with-margin"]}`}>
          <View className={style["small-title"]}>申请理由</View>
          <Picker
            className={style["reason-input"]}
            range={refundReasons}
            mode="selector"
            onChange={(e) => {
              setReason(refundReasons[e.detail.value]);
            }}
          >
            <View
              className={`${style["reason"]} ${
                hasReason ? style["selected"] : null
              }`}
            >
              <View>{!hasReason ? "请选择退款理由" : reason}</View>
              <Icon className={style.down} type="DownChevron" />
            </View>
          </Picker>
        </View>

        {/* Items */}
        <View
          className={`title-s ${style["cart-items-listing"]} ${style["section"]}`}
        >
          <View className={style["small-title"]}>退款商品</View>
          {items.map((item, index) => {
            return (
              <View
                key={`${item.itemType}-${item.productId}`}
                className={style["cart-item-container"]}
              >
                <View className={style["checkbox-grouping"]}>
                  <CheckboxGroup
                    className={style["checkbox-group"]}
                    onChange={(e) => {
                      const checked = !!e.detail.value.length;
                      handleCheckbox(checked, item);
                    }}
                  >
                    <Checkbox
                      value={`${item.productId}`}
                      checked={checkedItems.includes(item.productId)}
                    />
                    <View className={style["checkbox-bg"]} />
                    <View
                      className={style["checkbox-active"]}
                      style={{
                        opacity: checkedItems.includes(item.productId) ? 1 : 0,
                      }}
                    />
                  </CheckboxGroup>
                </View>
                {/* Left side */}
                <AbstractImage
                  type="about-sub-page-list"
                  src={item.imagePath}
                />
                {/* Right side */}
                <View className={style["content-container"]}>
                  <View className={style["top-content-container"]}>
                    <View
                      className={`title-s ${style["cart-items-title"]}`}
                      style={{ color: item.tagColor }}
                    >
                      {item.categoryName || item.tag}
                    </View>

                    <View className={style["name"]}>{item.name}</View>

                    {/* Quantity selector - During testing need to see if clickable area large enough */}
                    <View className={style["quantity"]}>x{item.quantity}</View>
                  </View>

                  {/* Price */}
                  <PriceView
                    className={style["price"]}
                    price={item.unitPrice * item.quantity}
                    type="small"
                  />
                </View>
              </View>
            );
          })}
        </View>

        {/* Summary/Total/Terms */}
        <View
          className={`${style["cost-summary"]} ${style["section"]} ${style["with-margin"]}`}
        >
          <View className={style["checkbox-grouping"]}>
            <CheckboxGroup
              className={style["checkbox-group"]}
              onChange={(e) => {
                const checked = !!e.detail.value.length;
                if (checked) {
                  checkAll();
                }
              }}
            >
              <Label>
                <Checkbox
                  className={style["smaller-padding"]}
                  value="ALL"
                  checked={isAllChecked}
                />
                <View className={style["checkbox-bg"]} />
                <View
                  className={style["checkbox-active"]}
                  style={{
                    opacity: isAllChecked ? 1 : 0,
                  }}
                />
                全选
              </Label>
            </CheckboxGroup>
          </View>
          <View className={style["price-container"]}>
            <Paragraph color={colors.colorDark} size="small" noSpacing>
              商品最多可退款
            </Paragraph>
            <PriceView
              className={style["price-view"]}
              price={items.reduce(
                (sum, item) =>
                  sum +
                  (checkedItems.includes(item.productId)
                    ? item.quantity * item.unitPrice
                    : 0),
                0
              )}
              type="heading-n"
              zeroAsNumber
            />
          </View>
        </View>

        <View className={style["small-title"]}>补充信息</View>
        <Textarea
          className={style["additional-input"]}
          value={additional}
          placeholder="0/140"
          onInput={(e) => {
            setAdditional(e.detail.value);
          }}
        />

        {/* Bottom dock */}
        <View className={style["bottom-dock-wrapper"]}>
          <C13BottomDock
            onPrimaryClick={{
              text: "提交申请",
              disabled: !checkedItems.length,
              cb: () => {
                handleSubmit(reason, additional);
              },
            }}
            onSecondaryClick={null}
          />
        </View>
      </View>
    </UserSubPageBase>
  );
};

export default C41RefundList;
